package org.cresource.order.service.impl;


import org.cresource.basic.service.impl.BaseServiceImpl;
import org.cresource.basic.util.CodeGenerateUtils;
import org.cresource.order.domain.AdoptOrder;
import org.cresource.order.domain.OrderAddress;
import org.cresource.order.mapper.AdoptOrderMapper;
import org.cresource.order.mapper.OrderAddressMapper;
import org.cresource.order.service.IAdoptOrderService;
import org.cresource.org.mapper.EmployeeMapper;
import org.cresource.pay.constants.PayConstants;
import org.cresource.pay.domain.PayBill;
import org.cresource.pay.mapper.PayBillMapper;
import org.cresource.pay.service.IPayBillService;
import org.cresource.pet.domain.Pet;
import org.cresource.pet.mapper.PetMapper;
import org.cresource.quartz.domain.QuartzJobInfo;
import org.cresource.quartz.service.IQuartzService;
import org.cresource.user.domain.LoginInfo;
import org.cresource.user.domain.User;
import org.cresource.user.domain.UserAddress;
import org.cresource.user.mapper.LoginInfoMapper;
import org.cresource.user.mapper.UserAddressMapper;
import org.cresource.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdoptOrderServiceImpl extends BaseServiceImpl<AdoptOrder> implements IAdoptOrderService {
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AdoptOrderMapper adoptOrderMapper;
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PayBillMapper payBillMapper;
    @Autowired
    private IPayBillService payBillService;
    @Autowired
    IQuartzService quartzService;



    @Override
    @Transactional
    public String submit(Map<String, Object> params, LoginInfo loginInfo) {
        // 获取map中的参数
        Long petId = Long.valueOf(params.get("pet_id").toString());                          // 获取宠物的id
        Long addressId = Long.valueOf(params.get("address_id").toString());                  // 收货地址：t_user_address的id
        Integer serviceMethod = Integer.valueOf(params.get("service_method").toString());    // 送货方式
        Integer payMethod = Integer.valueOf(params.get("pay_method").toString());            // 1 支付宝 2 微信  3 银联 0 余额
        // 修改宠物状态 -- 下架
        Pet pet = petMapper.loadById(petId);
        pet.setState(0);                    // 下架
        pet.setOffsaletime(new Date());     // 生成下架时间
        // 绑定领养的用户
        User user = userMapper.loadByloingInfoId(loginInfo.getId());
        pet.setUser(user);
        pet.setUser_id(user.getId());
        pet.setShop_id(pet.getShop().getId());
        // 修改宠物数据
        petMapper.update(pet);
        // 生成领养订单
        AdoptOrder adoptOrder = getAdoptOrder(pet, petId, user);
        // 生成统一的支付单号 -- 生成支付单的时候直接拿
        String unionPaySn = CodeGenerateUtils.generateUnionPaySn();
        adoptOrder.setPaySn(unionPaySn);
        adoptOrderMapper.save(adoptOrder);
        // 生成订单地址
        UserAddress userAddress = userAddressMapper.loadById(addressId); // 用户地址
        OrderAddress orderAddress = userAddress2OrderAddress(adoptOrder, userAddress);
        orderAddressMapper.save(orderAddress);
        // 生成支付单
        PayBill payBill = initPayBill(payMethod, pet, user, adoptOrder);
        // 保存支付单
        payBillMapper.save(payBill);


        // 5.针对支付单添加定时任务
        QuartzJobInfo info = new QuartzJobInfo();
        info.setJobName(adoptOrder.getPaySn());//定时任务的唯一标识
        Map<String, Object> map = new HashMap<>();
        map.put("orderSn", payBill.getUnionPaySn());
        // 定时任务 需要的 数据
        info.setParams(map);

        info.setFireDate(payBill.getLastPayTime());//最后的支付时间，定时任务的执行时间

        quartzService.addQuartz(info);




        // 调用统一的支付接口完成支付
        String resultData = payBillService.pay(payBill);
        return resultData;
        // 订单定时取消任务@TODO
    }




    /**
     * 初始化支付单
     * @param payMethod
     * @param pet
     * @param user
     * @param adoptOrder
     * @return
     */
    private PayBill initPayBill(Integer payMethod, Pet pet, User user, AdoptOrder adoptOrder) {
        PayBill payBill = new PayBill();
        payBill.setDigest(adoptOrder.getDigest()+"支付单");
        payBill.setMoney(adoptOrder.getPrice());
        payBill.setUnionPaySn(adoptOrder.getPaySn());   // 支付唯一标识
        payBill.setState(0);  // 0待支付 1已支付 -1 取消
        payBill.setLastPayTime(new Date(System.currentTimeMillis() + PayConstants.LAST_TIME));
        payBill.setPayChannel(Long.valueOf(payMethod)); // 支付渠道
        payBill.setBusinessType(PayConstants.BUSINESS_TYPE_ADOPT); // 领养支付单
        payBill.setBusinessKey(adoptOrder.getId());
        payBill.setUser_id(user.getId());
        payBill.setShop_id(pet.getShop().getId());
        payBill.setNickName(user.getUsername());
        return payBill;
    }



    /**
     * 用户地址拷贝到订单地址
     * @param adoptOrder
     * @param userAddress
     * @return
     */
    private OrderAddress userAddress2OrderAddress(AdoptOrder adoptOrder, UserAddress userAddress) {
        OrderAddress orderAddress = new OrderAddress();                  // 订单地址
        BeanUtils.copyProperties(userAddress, orderAddress);             // 调用工具类拷贝
        orderAddress.setId(null);                                        // id自增，不用拷贝
        orderAddress.setOrderSn(adoptOrder.getOrderSn());                // 订单唯一标识
        orderAddress.setOrder_id(adoptOrder.getId());
        return orderAddress;
    }




    /**
     * 生成领养订单的信息
     * @param pet
     * @param petId
     * @param user
     * @return
     */
    private AdoptOrder getAdoptOrder(Pet pet,Long petId,User user){
        AdoptOrder adoptOrder = new AdoptOrder();
        // 摘要
        adoptOrder.setDigest("[摘要]领养"+pet.getName()+"的订单！");
        // 0 待支付 1 已支付
        adoptOrder.setState(0);
        // 售价
        adoptOrder.setPrice(pet.getSaleprice());
        // 订单唯一标识
        adoptOrder.setOrderSn(CodeGenerateUtils.generateOrderSn(pet.getId()));
        // 最后确定时间 -- 15分钟自动取消
        Date lastConfirmTime = new Date(System.currentTimeMillis() + PayConstants.LAST_TIME);
        adoptOrder.setLastConfirmTime(lastConfirmTime);
        // 宠物id
        adoptOrder.setPet_id(petId);
        // 用户id
        adoptOrder.setUser_id(user.getId());
        // 商店id
        adoptOrder.setShop_id(pet.getShop_id());
        // 返回
        return adoptOrder;
    }

}
